package com.seckill.goods.controller;

import com.seckill.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author：
 * @Description：
 ***/
@RestController
@RequestMapping(value = "/redis")
public class RedisTestController {

    @Autowired
    private RedisTemplate redisTemplate;

    /***
     * 数据存储
     */
    @GetMapping(value = "/cache/{cat}/{key}/{pc}/{cn}")
    public Result add(@PathVariable(value = "cat")String cat,
                      @PathVariable(value = "key")String key,
                      @PathVariable(value = "pc")Integer pc,
                      @PathVariable(value = "cn")Integer cn){
        //存入测试
        redisTemplate.boundHashOps("CAT_"+cat+":"+key).put("PC",pc);
        redisTemplate.boundHashOps("CAT_"+cat+":"+key).put("CN",cn);
        //获取测试
        List values = redisTemplate.boundHashOps("CAT_" + cat + ":" + key).values();
        return Result.ok(values);
    }

    /***
     * 数据获取
     */
    @GetMapping(value = "/cache/one/{cat}/{key}")
    public Result add(@PathVariable(value = "cat")String cat,
                      @PathVariable(value = "key")String key){
        //获取商品详情 价格+数量
        List values = redisTemplate.boundHashOps("CAT_" + cat + ":" + key).values();
        return Result.ok(values);
    }

    /***
     * 数据获取
     */
    @GetMapping(value = "/cache/one/cn/{cat}/{key}")
    public Result cn(@PathVariable(value = "cat")String cat,
                      @PathVariable(value = "key")String key){
        //获取价格
        Object cn = redisTemplate.boundHashOps("CAT_" + cat + ":" + key).get("CN");
        return Result.ok(cn);
    }

    /***
     * 数量递减
     */
    @GetMapping(value = "/cache/decr/{cat}/{key}")
    public Result decr(@PathVariable(value = "cat")String cat,
                      @PathVariable(value = "key")String key){
        //数量递减
        Long cn = redisTemplate.boundHashOps("CAT_" + cat + ":" + key).increment("CN", -1);
        return add(cat,key);
    }
}
